﻿using desktopEnglish.entity;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace desktopEnglish.utils
{
    class BiYingDict
    {

        public static Word getInfo(string word)
        {
            WebClient client = new WebClient();
            string url = "https://cn.bing.com/dict/search?q=" + word;
            byte[] page = null;
            try
            {
                page = client.DownloadData(url);
            }catch
            {
                MessageBox.Show("网络错误...........");
                Application.Exit();
            }
            if(page == null)
            {
                return new Word();
            }

            string content = System.Text.Encoding.UTF8.GetString(page);
            //单词的解释<meta name=\"description\"(\\S*).*?>
            Regex wordExplanRegex = new Regex("name=\"description\"\\scontent=\"必应词典.*? \"");
            Match wordExplanMatch = wordExplanRegex.Match(content);
            string wordExplan = wordDeal(word, wordExplanMatch.Value);

            //单词的的读音
            Regex pronRegex = new Regex("https://.*?\\.mp3");
            MatchCollection pronCollection = pronRegex.Matches(content);
            string usPron = "", ukPron = "";
            if (pronCollection.Count > 1)
            {
                usPron = pronCollection[0].Value;
                ukPron = pronCollection[1].Value;
            }
            Dictionary<string, string> dict = new Dictionary<string, string>();
            Word w = new Word(word, wordExplan, usPron,ukPron);
            return w;
        }

        private static string wordDeal(string word, string content)
        {
            //必应词典为您提供face的释义，
            string prefix = "必应词典为您提供" + word + "的释义，";
            string[] desc = content.Split("=");
            if (desc.Length > 2)
            {
                string explan = desc[2].Replace(prefix, "").Trim();
                return explan.Substring(1, explan.Length - 2);
            }
            return "";
        }
    }
}
